var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
(function (factory) {
    if (typeof module === "object" && typeof module.exports === "object") {
        var v = factory(require, exports);
        if (v !== undefined) module.exports = v;
    }
    else if (typeof define === "function" && define.amd) {
        define(["require", "exports", "services/shopping", "react", "maishu-dilu", "mobile/site", "react-dom", "maishu-wuzhui", "maishu-wuzhui-helper", "maishu-ui-toolkit"], factory);
    }
})(function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    const shopping_1 = require("services/shopping");
    const React = require("react");
    const maishu_dilu_1 = require("maishu-dilu");
    const site_1 = require("mobile/site");
    const ReactDOM = require("react-dom");
    const maishu_wuzhui_1 = require("maishu-wuzhui");
    const maishu_wuzhui_helper_1 = require("maishu-wuzhui-helper");
    const maishu_ui_toolkit_1 = require("maishu-ui-toolkit");
    class CouponCodeListPage extends React.Component {
        constructor(props) {
            super(props);
            this.state = { coupons: [], status: "all" };
            this.shopping = this.props.createService(shopping_1.ShoppingService);
        }
        switchTab(status) {
            if (status == this.state.status)
                return;
            switch (status) {
                case 'all':
                    this.gridView.selectArguments.filter = null;
                    break;
                case 'used':
                    this.gridView.selectArguments.filter = 'UsedDateTime <> null';
                    break;
                case 'canUse':
                    this.gridView.selectArguments.filter = `UsedDateTime == null and DateTime.Now.Date <= ValidEnd`;
                    break;
                case 'expired':
                    this.gridView.selectArguments.filter = `UsedDateTime == null and DateTime.Now.Date > ValidEnd`;
                    break;
            }
            this.dataSource.select(this.gridView.selectArguments);
            this.setState({ status });
        }
        status(couponCode) {
            var today = new Date();
            var dd = today.getDate();
            var mm = today.getMonth();
            var yyyy = today.getFullYear();
            var currentDate = new Date(yyyy, mm, dd);
            var text;
            var status;
            if (couponCode.UsedDateTime) {
                status = 'used';
                text = '已使用';
            }
            else if (currentDate > couponCode.ValidEnd) {
                status = 'expired';
                text = '已过期';
            }
            else {
                status = 'valid';
                text = '可使用';
            }
            return { value: status, text };
        }
        showGenerateDialog() {
            this.validator.clearErrors();
            maishu_ui_toolkit_1.showDialog(this.dialogElement);
        }
        generateCouponCode() {
            return __awaiter(this, void 0, void 0, function* () {
                let isValid = yield this.validator.check();
                if (isValid == false) {
                    return Promise.reject({});
                }
                let couponId = this.dialogElement['coupon'].value;
                let count = Number.parseInt(this.dialogElement['count'].value);
                return this.shopping.generateCouponCode(couponId, count).then(() => {
                    maishu_ui_toolkit_1.hideDialog(this.dialogElement);
                    return this.dataSource.select();
                });
            });
        }
        componentDidMount() {
            // this.validator = new FormValidator(this.dialogElement, {
            //     count: { rules: ['required'], display: '数量' },
            //     coupon: { rules: ['required'], messages: { required: '请选择优惠劵' } }//
            // });
            this.shopping.coupons({}).then(r => {
                // this.state.coupons = r.dataItems;
                // this.setState(this.state);
                this.setState({ coupons: r.dataItems });
            });
            let { required } = maishu_dilu_1.rules;
            // let e = this.dialogElement;
            this.validator = new maishu_dilu_1.FormValidator(this.dialogElement, { name: "count", rules: [required('请输入数量')] }, { name: "coupon", rules: [required('请选择优惠劵')] });
            this.dataSource = new maishu_wuzhui_1.DataSource({
                primaryKeys: ["Id"],
                select: (args) => {
                    return this.shopping.couponCodes(args);
                }
            });
            let self = this;
            this.gridView = maishu_wuzhui_helper_1.createGridView({
                element: this.couponCodesTable,
                dataSource: this.dataSource,
                columns: [
                    new maishu_wuzhui_1.BoundField({ dataField: 'Title', headerText: '名称' }),
                    new maishu_wuzhui_1.BoundField({ dataField: 'Code', headerText: '优惠码' }),
                    new maishu_wuzhui_1.CustomField({
                        createItemCell(data) {
                            let cell = new maishu_wuzhui_1.GridViewCell();
                            cell.element.innerHTML = `${site_1.formatDate(data.ValidBegin)} - ${site_1.formatDate(data.ValidEnd)}`;
                            return cell;
                        },
                        headerText: '有效期',
                        headerStyle: { width: '200px' },
                        itemStyle: { textAlign: 'center' }
                    }),
                    new maishu_wuzhui_1.BoundField({
                        dataField: 'UsedDateTime', headerText: '使用时间', dataFormatString: '{g}'
                    }),
                    new maishu_wuzhui_1.CustomField({
                        createItemCell(dataItem) {
                            let cell = new maishu_wuzhui_1.GridViewCell();
                            let status = self.status(dataItem);
                            ReactDOM.render(React.createElement("button", { className: "btn btn-minier btn-info", disabled: status.value != 'valid' }, status.text), cell.element);
                            return cell;
                        },
                        headerText: '状态',
                        headerStyle: { textAlign: 'center', width: '100px' },
                        itemStyle: { textAlign: 'center' }
                    })
                ]
            });
        }
        render() {
            let coupons = this.state.coupons || [];
            let status = this.state.status;
            return (React.createElement("div", null,
                React.createElement("div", { className: "tabbable" },
                    React.createElement("ul", { className: "nav nav-tabs" },
                        React.createElement("li", { className: status == "all" ? "active" : null },
                            React.createElement("a", { "data-toggle": "tab", onClick: () => this.switchTab('all') }, "\u5168\u90E8")),
                        React.createElement("li", { className: status == "canUse" ? "active" : null },
                            React.createElement("a", { "data-toggle": "tab", onClick: () => this.switchTab('canUse') }, "\u53EF\u4F7F\u7528")),
                        React.createElement("li", { className: status == "used" ? "active" : null },
                            React.createElement("a", { "data-toggle": "tab", onClick: () => this.switchTab('used') }, "\u5DF2\u4F7F\u7528")),
                        React.createElement("li", { className: status == "expired" ? "active" : null },
                            React.createElement("a", { "data-toggle": "tab", onClick: () => this.switchTab('expired') }, "\u5DF2\u8FC7\u671F")),
                        React.createElement("li", { className: "pull-right" },
                            React.createElement("button", { className: "btn btn-sm btn-primary" },
                                React.createElement("i", { className: "icon-download-alt" }),
                                React.createElement("span", null, "\u5BFC\u51FA"))),
                        React.createElement("li", { className: "pull-right" },
                            React.createElement("button", { className: "btn btn-sm btn-primary", ref: (o) => {
                                    if (!o)
                                        return;
                                    o.onclick = () => this.showGenerateDialog();
                                } },
                                React.createElement("i", { className: "icon-cog" }),
                                React.createElement("span", null, "\u751F\u6210\u4F18\u60E0\u7801"))),
                        React.createElement("li", { className: "pull-right" },
                            React.createElement("button", { id: "btnSearch", "data-bind": "click: search", className: "btn btn-sm btn-primary" },
                                React.createElement("i", { className: "icon-search" }),
                                React.createElement("span", null, "\u67E5\u627E"))),
                        React.createElement("li", { className: "pull-right" },
                            React.createElement("input", { "data-bind": "value: filter.searchText", id: "txtSearch", className: "nav-search-input form-control", type: "text", placeholder: "\u8F93\u5165\u8981\u67E5\u627E\u7684\u4F18\u60E0\u7801\u6216\u4F18\u60E0\u5238\u7F16\u53F7", style: { width: 300 } })))),
                React.createElement("table", { ref: (o) => this.couponCodesTable = o || this.couponCodesTable }),
                React.createElement("form", { className: "modal fade in", ref: (o) => this.dialogElement = o || this.dialogElement },
                    React.createElement("div", { className: "modal-dialog" },
                        React.createElement("div", { className: "modal-content" },
                            React.createElement("div", { className: "modal-header" },
                                React.createElement("button", { type: "button", className: "close", "data-dismiss": "modal" },
                                    React.createElement("span", { "aria-hidden": "true" }, "\u00D7"),
                                    React.createElement("span", { className: "sr-only" }, "Close")),
                                React.createElement("h4", { className: "modal-title" }, "\u751F\u6210\u4F18\u60E0\u7801")),
                            React.createElement("div", { className: "modal-body form-horizontal" },
                                React.createElement("div", { className: "form-group" },
                                    React.createElement("label", { className: "col-sm-2 control-label" }, "\u4F18\u60E0\u52B5"),
                                    React.createElement("div", { className: "col-sm-10" },
                                        React.createElement("select", { name: "coupon", className: "form-control", ref: (e) => this.couponsSelect = e || this.couponsSelect },
                                            React.createElement("option", { value: "" }, "\u8BF7\u9009\u62E9\u4F18\u60E0\u52B5"),
                                            coupons.map(o => React.createElement("option", { key: o.Id, value: o.Id }, o.Title))))),
                                React.createElement("div", { className: "form-group" },
                                    React.createElement("label", { className: "col-sm-2 control-label" }, "\u6570\u91CF"),
                                    React.createElement("div", { className: "col-sm-10" },
                                        React.createElement("input", { name: "count", type: "text", className: "form-control", placeholder: "\u8BF7\u8F93\u5165\u751F\u6210\u4F18\u60E0\u7801\u7684\u6570\u91CF", ref: (e) => this.countInput = e || this.countInput })))),
                            React.createElement("div", { className: "modal-footer" },
                                React.createElement("button", { type: "button", className: "btn btn-default", "data-dismiss": "modal" }, "\u53D6\u6D88"),
                                React.createElement("button", { type: "button", className: "btn btn-primary", ref: (o) => {
                                        if (!o)
                                            return;
                                        o.onclick = maishu_ui_toolkit_1.buttonOnClick(() => this.generateCouponCode());
                                    } }, "\u786E\u8BA4")))))));
        }
    }
    exports.default = CouponCodeListPage;
});
